package com.caigou.modules.data.ui.comment

import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.widget.ImageView
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.CommentItemBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.GlideEngine
import com.caigou.comm.databinding.ActivityReplyBinding
import com.caigou.modules.data.R
import com.caigou.modules.data.viewmodel.CommentViewModel
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.lwkandroid.widget.ngv.DefaultNgvAdapter
import com.lwkandroid.widget.ngv.NgvChildImageView
import dagger.hilt.android.AndroidEntryPoint
import java.io.File

/**
 * @author #Suyghur.
 * Created on 2021/12/04
 */
@Route(path = RouterPath.Data.PAGE_COMMENT_REPLY)
@AndroidEntryPoint
class CommentReplyActivity : BaseActivity() {

    private lateinit var binding: ActivityReplyBinding

    private val commentViewModel: CommentViewModel by viewModels()

    @Autowired(name = AppConstants.COMMENT_ITEM_BEAN)
    lateinit var itemBean: CommentItemBean

    @Autowired(name = AppConstants.COMMENT_ROOT_ITEM_BEAN)
    lateinit var rootItemBean: CommentItemBean

    @JvmField
    @Autowired(name = AppConstants.SUB_REPLY)
    var subReply = false

    private val urls: MutableList<String> = mutableListOf()

    private val mAdapter: DefaultNgvAdapter<String> by lazy {
        DefaultNgvAdapter(100, GlideDisplay())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityReplyBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.replyLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        binding.replyNgvDisplay.setSingleImageSize(TypedValue.COMPLEX_UNIT_DIP, 150, 200)
        mAdapter.setOnChildClickListener(object : DefaultNgvAdapter.OnChildClickedListener<String> {
            override fun onPlusImageClicked(plusImageView: ImageView?, dValueToLimited: Int) {
                openGallery()
            }

            override fun onContentImageClicked(position: Int, data: String?, childImageView: NgvChildImageView?) {
                data?.apply {
                    showImgsPreview(this@CommentReplyActivity, urls, urls.indexOf(this))
                }
            }

            override fun onImageDeleted(position: Int, data: String?) {
                data?.apply {
                    urls.remove(this)
                }
            }
        })
        binding.replyNgvDisplay.adapter = mAdapter
        binding.replyBtnSubmit.setOnClickListener {
            val content = binding.replyEtContent.text.toString()
            val files: MutableList<File> = mutableListOf()
            urls.forEach {
                files.add(File(it))
            }
            commentViewModel.setCommentReply(
                content,
                files,
                AppBackgroundInfo.instance.userBean!!.userId,
                itemBean.replyUserInfoVo.userId,
                itemBean.dataId,
                itemBean.type,
                rootItemBean.replyId
            )
        }
    }

    override fun observeViewModel() {
        observe(commentViewModel.commentReplyLiveData, ::handleSetCommentReply)
    }

    private fun handleSetCommentReply(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("留言失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                LiveDataBus.get().with(BusKey.REPLY_SUCCESS).value = Any()
                this.finish()
            }
        }
    }

    private fun openGallery() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .theme(R.style.picture_WeChat_style)
            .imageEngine(GlideEngine.instance)
            .imageSpanCount(4)
            .isReturnEmpty(true)
            .selectionMode(PictureConfig.MULTIPLE)
            .maxSelectNum(9)
            .isPreviewImage(true)
            .isCamera(true)
            .isZoomAnim(true)
            .setCameraImageFormat(PictureMimeType.PNG)
            .isEnableCrop(false)
            .isCompress(true)
            .compressQuality(80)
            .synOrAsy(false)
            .withAspectRatio(1, 1)
            .minimumCompressSize(100)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    result?.apply {
                        urls.clear()
                        forEach {
                            urls.add(it.compressPath)
                        }
                        mAdapter.dataList = urls
                    }
                }

                override fun onCancel() {
                }

            })
    }
}